<template>
  <div style="width: 100%; height: 100%; overflow: auto; padding: 20px">
    <el-timeline>
      <el-timeline-item
        v-for="(item, index) in currentItems"
        :key="index"
        :timestamp="item.timestamp"
        :hide-timestamp="item.hideTimestamp"
        :placement="item.placement || 'bottom'"
        :type="item.type"
        :color="item.color"
        :size="item.size || 'normal'"
        :hollow="item.hollow"
        :icon="item.icon"
      >
        {{ item.content }}
      </el-timeline-item>
    </el-timeline>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElTimeline, ElTimelineItem } from 'element-plus';
import { useAutoDataBinding } from '@/composables/use-data-binding';
import { shouldUpdateChartData } from '@/utils/shallow-equal';
import type { IDataBindingConfig } from '@/components/mt-edit/store/types';

interface TimelineItem {
  content: string;
  timestamp?: string;
  hideTimestamp?: boolean;
  placement?: 'top' | 'bottom';
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info';
  color?: string;
  size?: 'normal' | 'large';
  hollow?: boolean;
  icon?: string;
}

const props = defineProps({
  // 数据绑定配置
  dataBinding: {
    type: Object as () => IDataBindingConfig,
    default: () => ({
      enabled: false,
      sourceId: '',
      dataPointId: '',
      targetProperty: 'items',
      transform: 'array',
      defaultValue: '[]',
      updateInterval: 0,
      updateMode: 'replace'
    })
  },
  items: {
    type: Array as () => TimelineItem[],
    default: () => [
      {
        content: '创建任务',
        timestamp: '2024-01-01 10:00:00',
        type: 'primary'
      },
      {
        content: '任务进行中',
        timestamp: '2024-01-01 12:00:00',
        type: 'warning'
      },
      {
        content: '任务完成',
        timestamp: '2024-01-01 15:00:00',
        type: 'success'
      }
    ]
  }
});

// 响应式属性对象（用于数据绑定）
const componentProps = ref({
  items: props.items
});

// 使用数据绑定（hide属性由render-core处理，组件跳过）
const shouldUseDataBinding =
  props.dataBinding && props.dataBinding.enabled && props.dataBinding.targetProperty !== 'hide';

const dataBinding = useAutoDataBinding(
  shouldUseDataBinding ? props.dataBinding : null,
  componentProps.value,
  (property: string, value: any) => {
    // 直接更新响应式对象的属性
    if (componentProps.value.hasOwnProperty(property)) {
      (componentProps.value as any)[property] = value;
    }
  }
);

// 监听props变化，同步到响应式属性对象
// 性能优化：使用浅比较检查数组数据变化，避免不必要的重新渲染
watch(
  () => props.items,
  (newValue, oldValue) => {
    if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'items') {
      if (shouldUpdateChartData(newValue, oldValue)) {
        componentProps.value.items = [...newValue];
      }
    }
  },
  { deep: false }
);

// 使用计算属性来获取当前的时间线项数据
const currentItems = computed(() => {
  return componentProps.value.items;
});
</script>
